package pe.gob.onpe.util;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class FiltroSesion implements Filter {

  private FilterConfig config;

  /** Creates new SessionFilter */
  public FiltroSesion() {
  }

  public void init(FilterConfig filterConfig) throws ServletException {
    //System.out.println("Instance created of " + getClass().getName());
    this.config = filterConfig;
  }

  public void doFilter(ServletRequest request, 
		  				ServletResponse response, 
		  				FilterChain chain) throws java.io.IOException, ServletException {

	//Imprime el URI
	System.out.println("URI Request: "+ ((HttpServletRequest) request).getRequestURI());
	String requestURI = ((HttpServletRequest) request).getRequestURI();
	
    HttpSession session = ((HttpServletRequest) request).getSession();
    ServletContext context = config.getServletContext();
    /*
     * use the ServletContext.log method to log filter messages
     */
    // context.log("doFilter called in: " + config.getFilterName() + " on " + (new java.util.Date()));
    // log the session ID
    // context.log("session ID: " + session.getId());
    // Determina si está logueado por medio del nombre de usuario guardado en la sesion
    Long procesoElectoralId = (Long) session.getAttribute("procesoElectoralId");
    //Si no hay usuario registrado y es la ventana de login, pasar
    if (procesoElectoralId == null){
    	System.out.println("No tiene sesion: "+requestURI);
    	//Verificando que esté en la ventana de login
    	if("/SVENPWeb/".equals(requestURI) ||
    		"/SVENPWeb/Administracion/Menu/AutorizarUsuarioAction.do".equals(requestURI) ||
    		"/SVENPWeb/Administracion/AutorizarUsuarioAction.do".equals(requestURI) ||
    		"/SVENPWeb/EmitirVotoAction.do".equals(requestURI)){
    		chain.doFilter(request, response);
    	}else{
    		if(requestURI.contains("/SVENPWeb/Administracion")){
    			context.getRequestDispatcher("/Administracion/index.jsp").forward(request, response);
    		}else{
    			context.getRequestDispatcher("/").forward(request, response);
    		}
    	}
    }else{//Si ya tiene la sesión creada solo continuar con lo que le siga
		System.out.println("Tiene sesion: "+requestURI);
    	chain.doFilter(request, response);
    }
    //log a message about the log-in status
    //context.log("log-in status: " + (String) session.getAttribute("logged-in"));
    //context.log("");
  }

  public void destroy() {
    /*
     * called before the Filter instance is removed from service by the web
     * container
     */
  }
}